package com.clusterswisdom.horn.api.tmall.action.scitem;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.asny.TaskState;
import com.clusterswisdom.horn.api.db.TaskDbUtil;
import com.clusterswisdom.horn.api.db.cursor.TaskItemCursor;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.scitem.model.ScItem;
import com.clusterswisdom.horn.api.tmall.action.scitem.model.Store;
import com.clusterswisdom.horn.api.tmall.action.scitem.model.StoreInfo;
import com.taobao.api.domain.InventorySum;
import com.taobao.api.response.InventoryAdjustExternalResponse;
import com.taobao.api.response.InventoryQueryResponse;
import com.taobao.api.response.ScitemOutercodeGetResponse;

/**
 * 区域库存调整
 * @author Jin_tian
 *
 */
public class ExtendStoreAction extends InitialStoryAction implements HornAction{
	
	@Override
	public HornResponse execute(ApiConfig config, JSONObject param) throws Exception {
		Long taskId = param.getLong("TASK_ID");
		TaskDbUtil.updateTaskState(taskId, TaskState.PROCESSING.getValue());
		
		try {
			TaskItemCursor itemCursor = TaskDbUtil.getTaskItemsConnection(taskId);
			
			
		} catch (Exception e) {
			e.printStackTrace();
			
		} finally {
			
			
		}
		
		
		
		StoreInfo inputInfo = getInputStoreInfo(param);
		StoreInfo nowInfo = getNowStoreInfo(inputInfo);
		String failedRespones = setStoreInfo(inputInfo, nowInfo);
		if (failedRespones.length() == 0) {
			return new HornResponse(true, null);
			
		} else {
			return new HornResponse(false, failedRespones);
			
		}
	}
	
	private String setStoreInfo(StoreInfo inputInfo, StoreInfo nowInfo) throws Exception {
		Iterator<Store> storeIterator = inputInfo.values().iterator();
		StringBuilder resultBuilder = new StringBuilder(100);
		
		while (storeIterator.hasNext()) {
			Store inputStore = storeIterator.next();
			Store nowStore = nowInfo.get(inputStore.getCode());
			
			InventoryAdjustExternalResponse response = setItemStoreInfo(inputStore, nowStore);
			if (!response.isSuccess()) {
				resultBuilder.append(getUnsuccessResponse(response)).append(";");
			}
		}
		
		return resultBuilder.toString();
	}
	
	private InventoryAdjustExternalResponse setItemStoreInfo(Store inputStore, Store nowStore) throws Exception {
		JSONObject param = new JSONObject();
		param.put("biz_unique_code", Long.toString(System.currentTimeMillis()));
		param.put("operate_type", "BALANCE");
		param.put("biz_type", "BALANCE");
		param.put("operate_time", new Date());
		param.put("store_code", inputStore.getCode());
		param.put("items",getStoreItemParam(inputStore, nowStore));
		
		return (InventoryAdjustExternalResponse)TmallInstance.getInstance().executeRequest(param,"scitem","inventoryadjustexternal");
	}
	
	private String getStoreItemParam(Store inputStore, Store nowStore) {
		JSONArray itemArray = new JSONArray();
		
		Iterator<ScItem> itemIterator = inputStore.values().iterator();
		while (itemIterator.hasNext()) {
			ScItem inpuItem = itemIterator.next();
			ScItem nowImte = nowStore.get(inpuItem.getItemId());
			Long span = getQuantitySpan(inpuItem, nowImte);
			
			JSONObject item = new JSONObject();
			item.put("scItemId", "0");
			item.put("scItemCode", inpuItem.getItemId());
			item.put("inventoryType", "1");
			item.put("direction", span < 0 ? "-1" : "1");
			item.put("quantity", Long.toString(Math.abs(span)));
			
			itemArray.add(item);
		}
		
		return JSON.toJSONString(itemArray);
	}
	
	private Long getQuantitySpan(ScItem inputItem, ScItem nowItem) {
		Long inputQuantity = null;
		if (inputItem != null) {
			inputQuantity = inputItem.getQuantity();
		}
		
		Long nowQuantity = null;
		if (nowItem != null) {
			nowQuantity = nowItem.getQuantity();
		}
		
		if (nowQuantity == null) {
			return inputQuantity;
		}
		
		if (inputQuantity == null || inputQuantity == 0) {
			return 0l;
		}
		
		return nowQuantity - inputQuantity;
	}
	
	private StoreInfo getNowStoreInfo(StoreInfo inputInfo) throws Exception {
		StoreInfo storeInfo = new StoreInfo();
		List<String> items = inputInfo.getAllItems();
		
		for (int i = 0; i < items.size(); i+= 50) {
			JSONObject param = new JSONObject();
			param.put("sc_item_ids", getFetchItemIds(items, i));
			
			InventoryQueryResponse response = (InventoryQueryResponse)TmallInstance.getInstance().executeRequest(param,"scitem","inventoryquery");
			for (InventorySum inventorySum : response.getItemInventorys()) {
				storeInfo.addStore(inventorySum.getStoreCode(), inventorySum.getScItemCode(), inventorySum.getQuantity());
			}
		}
		
		return storeInfo;
	}
	
	private String getFetchItemIds(List<String> items, int index) throws Exception {
		StringBuilder idsBuild = new StringBuilder(100);
		String separtor = "";
		
		for (int i = index; i < index + 50 && i < items.size(); i++) {
			idsBuild.append(separtor);
			String item = items.get(i);
			
			JSONObject param = new JSONObject();
			param.put("outer_code", item);
			
			ScitemOutercodeGetResponse response = (ScitemOutercodeGetResponse)TmallInstance.getInstance().executeRequest(param, "scitem", "scitemOutercodeGet");
			idsBuild.append(Long.toString(response.getScItem().getItemId()));
			
			separtor = "^";
		}
		
		return idsBuild.toString();
	}
}
